<?php
/**
 * @version	$Id: categories.php 17 2011-01-30 01:54:20Z gregdaynes@gmail.com $
 * @package	jEvolve.SyncrClient
 * @copyright  Copyright (C) 2010 jEvolve, LLC. All rights reserved.
 * @license	GNU General Public License
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class SyncrModelCategories extends JModel
{
	var $_log = null;
	
	function __construct() {
		parent::__construct();
		
		// new class
		$evl = new evolveLibrary;
		
		// load some evl stuff
		$this->_log = $evl->loadHelper('log');
	}
	
	public function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data)) {
			$this->_data = $this->_buildQuery();
		}
				
		if (is_array($this->_data)) {
			return json_encode($this->_data);
		}
	}
	
	private function _buildQuery()
	{
		$db = &JFactory::getDBO();
		
		$query = 'SELECT c.id'
			  .', CONCAT_WS(" - ", s.title, c.title) AS title'
			   .' FROM #__categories AS c'
			   .' JOIN #__sections AS s ON s.id = c.section'
			   .$this->_buildWhere()
			   .' ORDER BY s.title, c.title ASC'
			   ;
		
		$db->setQuery($query);
		$results = $db->loadAssocList();
		
		if (!count($results)) {
			$this->_log->simpleLog('categories.php/_buildQuery: could not find categories', 'syncr');
			
			JError::raiseWarning(500, JText::_('Could not find categories'));
		}
				
		return $results;
	}
	
	private function _buildWhere()
	{
		$params = &JComponentHelper::getParams( 'com_syncrclient' );
		
		if ($published_only = $params->get('published_only')) {
			$where[] = 'c.published = 1';
		}
		
		$where[] = 'c.checked_out = 0';
		
		return ' WHERE ' . implode(' AND ', $where);
	}
}